'use client';

import './style.scss';
import '../../crew/widget/style.scss';
import { useState, useEffect, useCallback } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
import { fetchApi } from '@/lib/utils/client';
import { useStudioContext } from '@/app/studio/context';
import type { CrewItem, CrewListResponse } from '@/types/response/crew/list';
import { Button } from '@/components/ui/button';
import CrewSettingsTab from './_components/CrewSettingsTab';
import CrewMembersTab from './_components/CrewMembersTab';
import CrewWidgetTab from './_components/CrewWidgetTab';
import CrewSessionTab from './_components/CrewSessionTab';

const TABS = [
	{ key: 'settings', label: '기본 설정' },
	{ key: 'members', label: '크루원' },
	{ key: 'widget', label: '위젯' },
	{ key: 'session', label: '세션' }
] as const;

type TabKey = typeof TABS[number]['key'];

export default function CrewDetailPage()
{
	const { id } = useParams<{ id: string }>();
	const { channelID } = useStudioContext();
	const crewID = Number(id);

	const [crew, setCrew] = useState<CrewItem|null>(null);
	const [loading, setLoading] = useState(true);
	const [activeTab, setActiveTab] = useState<TabKey>('members');

	const fetchCrew = useCallback(async () => {
		if (!channelID) return;
		try {
			const res = await fetchApi<CrewListResponse>(`/api/studio/crew/list/${channelID}`);
			const found = res.data?.list.find(c => c.id === crewID);
			if (found) setCrew(found);
		} catch {}
	}, [channelID, crewID]);

	useEffect(() => {
		setLoading(true);
		fetchCrew().finally(() => setLoading(false));
	}, [fetchCrew]);

	if (loading) {
		return <div className="studio-page"><p className="studio-page__empty">준비 중...</p></div>;
	}

	if (!crew) {
		return <div className="studio-page"><p className="studio-page__empty">크루를 찾을 수 없습니다.</p></div>;
	}

	return (
		<div className="studio-page crew-detail">
			{/* 헤더: 제목 + 액션 버튼 */}
			<div className="crew-detail__header">
				<div className="crew-detail__info">
					<h1 className="crew-detail__title">{crew.name}</h1>
					{crew.description && <p className="crew-detail__desc">{crew.description}</p>}
				</div>
				<div className="crew-detail__actions">
					<Button variant="outline" size="sm" asChild>
						<Link href="/studio/donation/crew">＜ 목록으로</Link>
					</Button>
				</div>
			</div>

			{/* 탭 네비게이션 */}
			<nav className="crew-tabs">
				{TABS.map(tab => (
					<button
						type="button"
						key={tab.key}
						className={`crew-tabs__item${activeTab === tab.key ? ' crew-tabs__item--active' : ''}`}
						onClick={() => setActiveTab(tab.key)}
					>
						{tab.label}
					</button>
				))}
			</nav>

			{/* 탭 컨텐츠 */}
			<div className="crew-tabs__content">
				{activeTab === 'settings' && <CrewSettingsTab crew={crew} onUpdated={fetchCrew} />}
				{activeTab === 'members' && <CrewMembersTab crewID={crewID} />}
				{activeTab === 'widget' && <CrewWidgetTab crewID={crewID} />}
				{activeTab === 'session' && <CrewSessionTab crewID={crewID} />}
			</div>
		</div>
	);
}